/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_upload_large.htm
 *
 * Zhiqim UploadLarge is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.uploadlarge;

import java.io.File;
import java.sql.SQLException;
import java.util.List;

import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.schedule.Task;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.uploadlarge.dbo.UpllChunk;

/**
 * 大文件上传数据库任务
 * 1)把前一天的碎片文件删除掉，包括文件
 *
 * @version v1.0.0 @author zouzhigang 2017-7-19 新建与整理
 */
public class ZulTask implements ZulConstants,Task
{
    private static final Log log = LogFactory.getLog(ZulTask.class);
    
    @Override
    public void execute()
    {
        String datetime = DateTimes.getDateString() + " 00:00:00";
        String chunkTime = DateTimes.getPreviousDateTimeString(datetime, 1);
        
        Selector selector = new Selector().addMustThenL("chunkTime", Sqls.toTimestamp(chunkTime));
        
        try
        {
            List<UpllChunk> list = ORM.table().list(UpllChunk.class, selector);
            int size = list.size();
            int error = 0;
            
            for (UpllChunk chunk : list)
            {
                String filePath = chunk.getFileTempPath();
                if (Validates.isEmptyBlank(filePath))
                {
                    deleteChunk(chunk);
                    continue;
                }
                    
                File file = new File(filePath);
                if (!file.exists())
                {
                    deleteChunk(chunk);
                    continue;
                }
                
                if (file.delete())
                    deleteChunk(chunk);
                else
                    error++;
            }
            
            log.info("删除[%s]之前的碎片文件完成，总[%s]，失败[%s]...", chunkTime, size, error);
        }
        catch (Exception e)
        {
            log.error("删除[%s]之前的碎片文件时异常", chunkTime, e);
        }
    }
    
    /** 删除碎片 */
    private void deleteChunk(UpllChunk chunk) throws ORMException, SQLException
    {
        ORM.table().delete(UpllChunk.class, chunk.getFileMd5(), chunk.getChunkSize());
    }
}
